package prototype;

class M implements Cloneable{
    int y = 1;

    @Override
    public String toString() {
        return "M{" +
                "y=" + y +
                '}';
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

class Person implements Cloneable{
    int x = 1;
    M m = new M();

    @Override
    public String toString() {
        return "Person{" +
                "x=" + x +
                ", m=" + m +
                '}';
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        // 拷贝 通过父类的super.clone复制出来
        Person p = (Person) super.clone();

        // 深拷贝
        p.m = (M) m.clone();

        return p;
    }
}

public class Prototype {
    public static void main(String[] args) {
        System.out.println("prototype");
        Person person = new Person();

        try {
            Person cperson = (Person)person.clone();
            cperson.m.y = 100; // 因为对象内部有对象默认是前拷贝所以该这里原来的也改变的
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }

        System.out.println(person);
    }
}
